﻿using System.Collections.Generic;
using SillyCube.Level;
using UnityEngine;

namespace SillyCube
{
    public class LevelManager : MonoBehaviour
    {
        private LevelBase _level = null;
        public LevelBase CurrentLevel => _level;
        
        [SerializeField] private List<GameObject> levelPrefabs;
        
        public LevelBase LoadLevel(int id, bool destroyLoaded = true)
        {
            if (id < 0 || id >= levelPrefabs.Count)
            {
                Debug.LogWarning("Error: Level Manager: No level with idx = " + id);
                return null;
            }

            var prefab = levelPrefabs[id];
            if (prefab == null)
            {
                Debug.LogWarning("Error: Level Manager: No level with id = " + id);
                return null;
            }

            if (destroyLoaded && _level != null)
            {
                Destroy(_level.gameObject);
            }
            
            var level = Instantiate(prefab, transform);
            _level = level.GetComponent<LevelBase>();

            return _level;
        }
    }
}